#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    int fd=open("JK",O_RDWR|O_CREAT|O_TRUNC,0666);
    if(fd<0)
    {
        perror("open fail");
        exit(1);
    }

    //向指定文件JK中写入数据
    const char* str="i like linux!\n";
    ssize_t rw=write(fd,str,strlen(str));
    if(rw<0)
    {
        perror("write fail");
        exit(2);
    }
    

    //将内核缓冲区的数据刷新到文件中
    syncfs(fd);
    //归位指针
    lseek(fd,0,SEEK_SET);

    //从文件中读取
    char buff[1024]={0};
    memset(buff,0,sizeof(buff));
    ssize_t rr=read(fd,buff,sizeof(buff));
    if(rr<0)
    {
        perror("read fail");
        exit(3);
    }
    else if(rr==0)
    {
        perror("end of read");
        exit(4);
    }
    buff[rr]='\0';
    printf("buff:%s",buff);

    

    close(fd);
    return 0;
}